class VectorCoordinateSystem {
    constructor() {
        this.canvas = document.getElementById('coordinateCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.vectors = [];
        this.gridSize = 40;
        this.showGrid = true;
        this.origin = { x: this.canvas.width / 2, y: this.canvas.height / 2 };
        
        this.initializeEventListeners();
        this.draw();
    }
    
    initializeEventListeners() {
        // 添加向量按钮
        document.getElementById('addVector').addEventListener('click', () => {
            this.addVector();
        });
        
        // 清除所有向量按钮
        document.getElementById('clearAll').addEventListener('click', () => {
            this.clearAllVectors();
        });
        
        // 导出PNG按钮
        document.getElementById('exportPNG').addEventListener('click', () => {
            this.exportPNG();
        });
        
        // 导出SVG按钮
        document.getElementById('exportSVG').addEventListener('click', () => {
            this.exportSVG();
        });
        
        // 网格大小滑块
        const gridSizeSlider = document.getElementById('gridSize');
        gridSizeSlider.addEventListener('input', (e) => {
            this.gridSize = parseInt(e.target.value);
            document.getElementById('gridSizeValue').textContent = this.gridSize;
            this.draw();
        });
        
        // 显示网格复选框
        document.getElementById('showGrid').addEventListener('change', (e) => {
            this.showGrid = e.target.checked;
            this.draw();
        });
        
        // 鼠标移动显示坐标
        this.canvas.addEventListener('mousemove', (e) => {
            this.updateMouseCoordinates(e);
        });
        
        // 点击画布添加向量
        this.canvas.addEventListener('click', (e) => {
            this.addVectorFromClick(e);
        });
        
        // 回车键添加向量
        ['vectorName', 'vectorX', 'vectorY'].forEach(id => {
            document.getElementById(id).addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.addVector();
                }
            });
        });
    }
    
    addVector() {
        const name = document.getElementById('vectorName').value.trim();
        const x = parseFloat(document.getElementById('vectorX').value) || 0;
        const y = parseFloat(document.getElementById('vectorY').value) || 0;
        const color = document.getElementById('vectorColor').value;
        
        if (!name) {
            alert('请输入向量名称');
            return;
        }
        
        // 检查名称是否重复
        if (this.vectors.some(v => v.name === name)) {
            alert('向量名称已存在，请使用不同的名称');
            return;
        }
        
        const vector = {
            id: Date.now(),
            name: name,
            x: x,
            y: y,
            color: color
        };
        
        this.vectors.push(vector);
        this.updateVectorList();
        this.draw();
        this.clearInputs();
    }
    
    addVectorFromClick(e) {
        const rect = this.canvas.getBoundingClientRect();
        const canvasX = e.clientX - rect.left;
        const canvasY = e.clientY - rect.top;
        
        // 转换为数学坐标
        const mathX = (canvasX - this.origin.x) / this.gridSize;
        const mathY = (this.origin.y - canvasY) / this.gridSize;
        
        // 四舍五入到一位小数
        const roundedX = Math.round(mathX * 10) / 10;
        const roundedY = Math.round(mathY * 10) / 10;
        
        // 填充输入框
        document.getElementById('vectorX').value = roundedX;
        document.getElementById('vectorY').value = roundedY;
        
        // 如果名称为空，自动生成
        if (!document.getElementById('vectorName').value.trim()) {
            document.getElementById('vectorName').value = `v${this.vectors.length + 1}`;
        }
    }
    
    deleteVector(id) {
        this.vectors = this.vectors.filter(v => v.id !== id);
        this.updateVectorList();
        this.draw();
    }
    
    clearAllVectors() {
        if (this.vectors.length === 0) return;
        
        if (confirm('确定要清除所有向量吗？')) {
            this.vectors = [];
            this.updateVectorList();
            this.draw();
        }
    }
    
    clearInputs() {
        document.getElementById('vectorName').value = '';
        document.getElementById('vectorX').value = '';
        document.getElementById('vectorY').value = '';
        document.getElementById('vectorName').focus();
    }
    
    updateVectorList() {
        const container = document.getElementById('vectorListContainer');
        
        if (this.vectors.length === 0) {
            container.innerHTML = '<p class="empty-state">暂无向量</p>';
            return;
        }
        
        container.innerHTML = this.vectors.map(vector => `
            <div class="vector-item">
                <div style="display: flex; align-items: center;">
                    <div class="vector-color" style="background-color: ${vector.color}"></div>
                    <div class="vector-info">
                        <div class="vector-name">${vector.name}</div>
                        <div class="vector-coords">(${vector.x}, ${vector.y})</div>
                    </div>
                </div>
                <div class="vector-actions">
                    <button class="btn-small btn-delete" onclick="vectorSystem.deleteVector(${vector.id})">
                        删除
                    </button>
                </div>
            </div>
        `).join('');
    }
    
    updateMouseCoordinates(e) {
        const rect = this.canvas.getBoundingClientRect();
        const canvasX = e.clientX - rect.left;
        const canvasY = e.clientY - rect.top;
        
        // 转换为数学坐标
        const mathX = (canvasX - this.origin.x) / this.gridSize;
        const mathY = (this.origin.y - canvasY) / this.gridSize;
        
        document.getElementById('mouseCoords').textContent = 
            `鼠标坐标: (${mathX.toFixed(1)}, ${mathY.toFixed(1)})`;
    }
    
    draw() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格
        if (this.showGrid) {
            this.drawGrid();
        }
        
        // 绘制坐标轴
        this.drawAxes();
        
        // 绘制向量
        this.drawVectors();
        
        // 绘制刻度
        this.drawScale();
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#f0f0f0';
        this.ctx.lineWidth = 1;
        
        // 垂直线
        for (let x = 0; x <= this.canvas.width; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        
        // 水平线
        for (let y = 0; y <= this.canvas.height; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }
    }
    
    drawAxes() {
        this.ctx.strokeStyle = '#333';
        this.ctx.lineWidth = 2;
        
        // X轴
        this.ctx.beginPath();
        this.ctx.moveTo(0, this.origin.y);
        this.ctx.lineTo(this.canvas.width, this.origin.y);
        this.ctx.stroke();
        
        // Y轴
        this.ctx.beginPath();
        this.ctx.moveTo(this.origin.x, 0);
        this.ctx.lineTo(this.origin.x, this.canvas.height);
        this.ctx.stroke();
        
        // 箭头
        this.drawArrow(this.canvas.width - 10, this.origin.y, this.canvas.width, this.origin.y);
        this.drawArrow(this.origin.x, 10, this.origin.x, 0);
        
        // 轴标签
        this.ctx.fillStyle = '#333';
        this.ctx.font = '14px Arial';
        this.ctx.fillText('X', this.canvas.width - 20, this.origin.y - 10);
        this.ctx.fillText('Y', this.origin.x + 10, 15);
    }
    
    drawScale() {
        this.ctx.fillStyle = '#666';
        this.ctx.font = '12px Arial';
        this.ctx.textAlign = 'center';
        
        // X轴刻度
        for (let i = -Math.floor(this.origin.x / this.gridSize); i <= Math.floor((this.canvas.width - this.origin.x) / this.gridSize); i++) {
            if (i === 0) continue;
            const x = this.origin.x + i * this.gridSize;
            this.ctx.fillText(i.toString(), x, this.origin.y + 15);
            
            // 刻度线
            this.ctx.strokeStyle = '#666';
            this.ctx.lineWidth = 1;
            this.ctx.beginPath();
            this.ctx.moveTo(x, this.origin.y - 5);
            this.ctx.lineTo(x, this.origin.y + 5);
            this.ctx.stroke();
        }
        
        // Y轴刻度
        this.ctx.textAlign = 'right';
        for (let i = -Math.floor((this.canvas.height - this.origin.y) / this.gridSize); i <= Math.floor(this.origin.y / this.gridSize); i++) {
            if (i === 0) continue;
            const y = this.origin.y - i * this.gridSize;
            this.ctx.fillText(i.toString(), this.origin.x - 10, y + 4);
            
            // 刻度线
            this.ctx.strokeStyle = '#666';
            this.ctx.lineWidth = 1;
            this.ctx.beginPath();
            this.ctx.moveTo(this.origin.x - 5, y);
            this.ctx.lineTo(this.origin.x + 5, y);
            this.ctx.stroke();
        }
    }
    
    drawVectors() {
        this.vectors.forEach(vector => {
            this.drawVector(vector);
        });
    }
    
    drawVector(vector) {
        const endX = this.origin.x + vector.x * this.gridSize;
        const endY = this.origin.y - vector.y * this.gridSize;
        
        // 绘制向量线
        this.ctx.strokeStyle = vector.color;
        this.ctx.lineWidth = 3;
        this.ctx.beginPath();
        this.ctx.moveTo(this.origin.x, this.origin.y);
        this.ctx.lineTo(endX, endY);
        this.ctx.stroke();
        
        // 绘制箭头
        this.drawArrow(this.origin.x, this.origin.y, endX, endY, vector.color);
        
        // 绘制向量标签
        this.ctx.fillStyle = vector.color;
        this.ctx.font = 'bold 14px Arial';
        this.ctx.textAlign = 'left';
        this.ctx.fillText(vector.name, endX + 5, endY - 5);
        
        // 绘制坐标标签
        this.ctx.font = '12px Arial';
        this.ctx.fillText(`(${vector.x}, ${vector.y})`, endX + 5, endY + 15);
    }
    
    drawArrow(fromX, fromY, toX, toY, color = '#333') {
        const headLength = 10;
        const angle = Math.atan2(toY - fromY, toX - fromX);
        
        this.ctx.strokeStyle = color;
        this.ctx.fillStyle = color;
        this.ctx.lineWidth = 2;
        
        // 箭头头部
        this.ctx.beginPath();
        this.ctx.moveTo(toX, toY);
        this.ctx.lineTo(
            toX - headLength * Math.cos(angle - Math.PI / 6),
            toY - headLength * Math.sin(angle - Math.PI / 6)
        );
        this.ctx.lineTo(
            toX - headLength * Math.cos(angle + Math.PI / 6),
            toY - headLength * Math.sin(angle + Math.PI / 6)
        );
        this.ctx.closePath();
        this.ctx.fill();
    }
    
    exportPNG() {
        // 创建一个临时canvas用于导出，背景为白色
        const exportCanvas = document.createElement('canvas');
        exportCanvas.width = this.canvas.width;
        exportCanvas.height = this.canvas.height;
        const exportCtx = exportCanvas.getContext('2d');
        
        // 设置白色背景
        exportCtx.fillStyle = '#ffffff';
        exportCtx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
        
        // 将原canvas内容绘制到导出canvas上
        exportCtx.drawImage(this.canvas, 0, 0);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.download = `向量图_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.png`;
        link.href = exportCanvas.toDataURL('image/png');
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    exportSVG() {
        const svgNS = 'http://www.w3.org/2000/svg';
        const svg = document.createElementNS(svgNS, 'svg');
        svg.setAttribute('width', this.canvas.width);
        svg.setAttribute('height', this.canvas.height);
        svg.setAttribute('viewBox', `0 0 ${this.canvas.width} ${this.canvas.height}`);
        svg.style.backgroundColor = '#ffffff';
        
        // 添加白色背景
        const background = document.createElementNS(svgNS, 'rect');
        background.setAttribute('width', '100%');
        background.setAttribute('height', '100%');
        background.setAttribute('fill', '#ffffff');
        svg.appendChild(background);
        
        // 绘制网格
        if (this.showGrid) {
            this.drawSVGGrid(svg, svgNS);
        }
        
        // 绘制坐标轴
        this.drawSVGAxes(svg, svgNS);
        
        // 绘制刻度
        this.drawSVGScale(svg, svgNS);
        
        // 绘制向量
        this.drawSVGVectors(svg, svgNS);
        
        // 创建下载链接
        const serializer = new XMLSerializer();
        const svgString = serializer.serializeToString(svg);
        const blob = new Blob([svgString], { type: 'image/svg+xml' });
        const url = URL.createObjectURL(blob);
        
        const link = document.createElement('a');
        link.download = `向量图_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.svg`;
        link.href = url;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        URL.revokeObjectURL(url);
    }
    
    drawSVGGrid(svg, svgNS) {
        const gridGroup = document.createElementNS(svgNS, 'g');
        gridGroup.setAttribute('stroke', '#f0f0f0');
        gridGroup.setAttribute('stroke-width', '1');
        
        // 垂直线
        for (let x = 0; x <= this.canvas.width; x += this.gridSize) {
            const line = document.createElementNS(svgNS, 'line');
            line.setAttribute('x1', x);
            line.setAttribute('y1', 0);
            line.setAttribute('x2', x);
            line.setAttribute('y2', this.canvas.height);
            gridGroup.appendChild(line);
        }
        
        // 水平线
        for (let y = 0; y <= this.canvas.height; y += this.gridSize) {
            const line = document.createElementNS(svgNS, 'line');
            line.setAttribute('x1', 0);
            line.setAttribute('y1', y);
            line.setAttribute('x2', this.canvas.width);
            line.setAttribute('y2', y);
            gridGroup.appendChild(line);
        }
        
        svg.appendChild(gridGroup);
    }
    
    drawSVGAxes(svg, svgNS) {
        const axesGroup = document.createElementNS(svgNS, 'g');
        axesGroup.setAttribute('stroke', '#333');
        axesGroup.setAttribute('stroke-width', '2');
        
        // X轴
        const xAxis = document.createElementNS(svgNS, 'line');
        xAxis.setAttribute('x1', 0);
        xAxis.setAttribute('y1', this.origin.y);
        xAxis.setAttribute('x2', this.canvas.width);
        xAxis.setAttribute('y2', this.origin.y);
        axesGroup.appendChild(xAxis);
        
        // Y轴
        const yAxis = document.createElementNS(svgNS, 'line');
        yAxis.setAttribute('x1', this.origin.x);
        yAxis.setAttribute('y1', 0);
        yAxis.setAttribute('x2', this.origin.x);
        yAxis.setAttribute('y2', this.canvas.height);
        axesGroup.appendChild(yAxis);
        
        // X轴箭头
        const xArrow = this.createSVGArrow(svgNS, this.canvas.width - 10, this.origin.y, this.canvas.width, this.origin.y, '#333');
        axesGroup.appendChild(xArrow);
        
        // Y轴箭头
        const yArrow = this.createSVGArrow(svgNS, this.origin.x, 10, this.origin.x, 0, '#333');
        axesGroup.appendChild(yArrow);
        
        // 轴标签
        const xLabel = document.createElementNS(svgNS, 'text');
        xLabel.setAttribute('x', this.canvas.width - 20);
        xLabel.setAttribute('y', this.origin.y - 10);
        xLabel.setAttribute('font-family', 'Arial');
        xLabel.setAttribute('font-size', '14');
        xLabel.setAttribute('fill', '#333');
        xLabel.textContent = 'X';
        axesGroup.appendChild(xLabel);
        
        const yLabel = document.createElementNS(svgNS, 'text');
        yLabel.setAttribute('x', this.origin.x + 10);
        yLabel.setAttribute('y', 15);
        yLabel.setAttribute('font-family', 'Arial');
        yLabel.setAttribute('font-size', '14');
        yLabel.setAttribute('fill', '#333');
        yLabel.textContent = 'Y';
        axesGroup.appendChild(yLabel);
        
        svg.appendChild(axesGroup);
    }
    
    drawSVGScale(svg, svgNS) {
        const scaleGroup = document.createElementNS(svgNS, 'g');
        scaleGroup.setAttribute('font-family', 'Arial');
        scaleGroup.setAttribute('font-size', '12');
        scaleGroup.setAttribute('fill', '#666');
        scaleGroup.setAttribute('text-anchor', 'middle');
        
        // X轴刻度
        for (let i = -Math.floor(this.origin.x / this.gridSize); i <= Math.floor((this.canvas.width - this.origin.x) / this.gridSize); i++) {
            if (i === 0) continue;
            const x = this.origin.x + i * this.gridSize;
            
            // 刻度文字
            const text = document.createElementNS(svgNS, 'text');
            text.setAttribute('x', x);
            text.setAttribute('y', this.origin.y + 15);
            text.textContent = i.toString();
            scaleGroup.appendChild(text);
            
            // 刻度线
            const tick = document.createElementNS(svgNS, 'line');
            tick.setAttribute('x1', x);
            tick.setAttribute('y1', this.origin.y - 5);
            tick.setAttribute('x2', x);
            tick.setAttribute('y2', this.origin.y + 5);
            tick.setAttribute('stroke', '#666');
            tick.setAttribute('stroke-width', '1');
            scaleGroup.appendChild(tick);
        }
        
        // Y轴刻度
        for (let i = -Math.floor((this.canvas.height - this.origin.y) / this.gridSize); i <= Math.floor(this.origin.y / this.gridSize); i++) {
            if (i === 0) continue;
            const y = this.origin.y - i * this.gridSize;
            
            // 刻度文字
            const text = document.createElementNS(svgNS, 'text');
            text.setAttribute('x', this.origin.x - 10);
            text.setAttribute('y', y + 4);
            text.setAttribute('text-anchor', 'end');
            text.textContent = i.toString();
            scaleGroup.appendChild(text);
            
            // 刻度线
            const tick = document.createElementNS(svgNS, 'line');
            tick.setAttribute('x1', this.origin.x - 5);
            tick.setAttribute('y1', y);
            tick.setAttribute('x2', this.origin.x + 5);
            tick.setAttribute('y2', y);
            tick.setAttribute('stroke', '#666');
            tick.setAttribute('stroke-width', '1');
            scaleGroup.appendChild(tick);
        }
        
        svg.appendChild(scaleGroup);
    }
    
    drawSVGVectors(svg, svgNS) {
        this.vectors.forEach(vector => {
            this.drawSVGVector(svg, svgNS, vector);
        });
    }
    
    drawSVGVector(svg, svgNS, vector) {
        const endX = this.origin.x + vector.x * this.gridSize;
        const endY = this.origin.y - vector.y * this.gridSize;
        
        const vectorGroup = document.createElementNS(svgNS, 'g');
        
        // 向量线
        const line = document.createElementNS(svgNS, 'line');
        line.setAttribute('x1', this.origin.x);
        line.setAttribute('y1', this.origin.y);
        line.setAttribute('x2', endX);
        line.setAttribute('y2', endY);
        line.setAttribute('stroke', vector.color);
        line.setAttribute('stroke-width', '3');
        vectorGroup.appendChild(line);
        
        // 箭头
        const arrow = this.createSVGArrow(svgNS, this.origin.x, this.origin.y, endX, endY, vector.color);
        vectorGroup.appendChild(arrow);
        
        // 向量标签
        const nameLabel = document.createElementNS(svgNS, 'text');
        nameLabel.setAttribute('x', endX + 5);
        nameLabel.setAttribute('y', endY - 5);
        nameLabel.setAttribute('font-family', 'Arial');
        nameLabel.setAttribute('font-size', '14');
        nameLabel.setAttribute('font-weight', 'bold');
        nameLabel.setAttribute('fill', vector.color);
        nameLabel.textContent = vector.name;
        vectorGroup.appendChild(nameLabel);
        
        // 坐标标签
        const coordLabel = document.createElementNS(svgNS, 'text');
        coordLabel.setAttribute('x', endX + 5);
        coordLabel.setAttribute('y', endY + 15);
        coordLabel.setAttribute('font-family', 'Arial');
        coordLabel.setAttribute('font-size', '12');
        coordLabel.setAttribute('fill', vector.color);
        coordLabel.textContent = `(${vector.x}, ${vector.y})`;
        vectorGroup.appendChild(coordLabel);
        
        svg.appendChild(vectorGroup);
    }
    
    createSVGArrow(svgNS, fromX, fromY, toX, toY, color) {
        const headLength = 10;
        const angle = Math.atan2(toY - fromY, toX - fromX);
        
        const arrowHead = document.createElementNS(svgNS, 'polygon');
        const x1 = toX - headLength * Math.cos(angle - Math.PI / 6);
        const y1 = toY - headLength * Math.sin(angle - Math.PI / 6);
        const x2 = toX - headLength * Math.cos(angle + Math.PI / 6);
        const y2 = toY - headLength * Math.sin(angle + Math.PI / 6);
        
        arrowHead.setAttribute('points', `${toX},${toY} ${x1},${y1} ${x2},${y2}`);
        arrowHead.setAttribute('fill', color);
        arrowHead.setAttribute('stroke', color);
        arrowHead.setAttribute('stroke-width', '2');
        
        return arrowHead;
    }
}

// 初始化系统
let vectorSystem;
document.addEventListener('DOMContentLoaded', () => {
    vectorSystem = new VectorCoordinateSystem();
});